package com.sendpo.zjx.sendpo.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.onlybeyond.numbertextview.NumberTextView;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.UserDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.OrderInfoUtil2_0;
import com.sendpo.zjx.sendpo.utils.PayDomain;
import com.sendpo.zjx.sendpo.utils.PayResult;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/8/son1.
 */

public class UserMoneyCenterActivity extends AppCompatActivity {


    @BindView(R.id.yue_zhanghu)
    TextView yueZhanghu;
    @BindView(R.id.ntv_test_nine)
    NumberTextView ntvTestNine;
    @BindView(R.id.listivew)
    ListView listivew;
    public static final String[] titles=new String[]{"充值","提现","银行卡"};
    public static  final int[] titles_res=new int[]{R.mipmap.chongzhi, R.mipmap.pay_tixian, R.mipmap.bank_icon};
    public Dialog dialog;
    public    RadioGroup radioGroup;
    public   EditText recharage_edit;




    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HttpUrl.SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Gson gson=new Gson();
                        PayDomain pay=gson.fromJson(payResult.getResult(),PayDomain.class);
                        addMoney(pay.getAlipay_trade_app_pay_response().getTotal_amount());
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        System.out.println("***************"+payResult.getResult());
                        Toast.makeText(getApplicationContext(), "支付成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(getApplicationContext(), "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        };
    };



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usermoneycenter);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        initComponent();
    }

    @Override
    protected void onStart() {
        super.onStart();
        locationUserServer();
        webUserServer();

    }

    public void webUserServer(){
        final List<User> userList= Xutils.queryAll(getApplication(),User.class);
        if(userList==null||userList.size()==0){
            return;
        }
        Map<String,String> map=new HashMap<>();
        map.put("userId",userList.get(0).getUserId()+"");
        Xutils.POST(HttpUrl.queryuserbyid, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                UserDomain userDomain= gson.fromJson(result,UserDomain.class);
                switch (userDomain.getState()){
                    case HttpCode.SUCCESS:
                        User user= userDomain.getData();
                        user.setId(userList.get(0).getId());
                        Xutils.update(getApplication(),user);
                        locationUserServer();
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    };

    public void locationUserServer(){
        final List<User> userList= Xutils.queryAll(getApplication(),User.class);
        if(userList==null||userList.size()==0){
            return;
        }
        User user=userList.get(0);
        System.out.println("*****************getUserMoney:"+user.getUserMoney());
        DecimalFormat decialFormat=new DecimalFormat("0.00");
        ntvTestNine.setNumberValue(decialFormat.format(Double.parseDouble(user.getUserMoney()))+"");
    }
    public void initComponent() {
        ntvTestNine.setMaxAnimDuration(1000);
        ntvTestNine.setUseMax(true);
        initMoney();
        listivew.setAdapter(new ListAdapter());
        listivew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                switch (i){
                    case 0:
                            recharage_edit.setText("");
                            dialog.show();
                        break;
                    case 1:
                        Tools.redirectActivity(UserMoneyCenterActivity.this,TixianActivity.class);
                        break;
                    case  2:
                        Tools.redirectActivity(UserMoneyCenterActivity.this,BankManagerActivity.class);
                        break;
                }
            }
        });

    }

    public void  initMoney(){
        dialog=new Dialog(this);
        dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog.setContentView(R.layout.dialog_rechargemoney);

        radioGroup=dialog.findViewById(R.id.rg_pay);
        TextView recharage_title=dialog.findViewById(R.id.recharage_title);
        recharage_title.setText("充值");
        View yuyue_left=dialog.findViewById(R.id.yuyue_left);
        yuyue_left.setVisibility(View.GONE);
        final RadioButton pay_moneypackage=dialog.findViewById(R.id.pay_moneypackage);
        pay_moneypackage.setVisibility(View.GONE);
        final RadioButton pay_paypackage=dialog.findViewById(R.id.pay_paypackage);
        final RadioButton pay_wexin=dialog.findViewById(R.id.pay_wexin);
        pay_wexin.setChecked(true);
        Button paybt=dialog.findViewById(R.id.paybt);
        paybt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(TextUtils.isEmpty(recharage_edit.getText().toString().trim())){
                    Toast.makeText(UserMoneyCenterActivity.this.getApplicationContext(),"不能什么都没有",Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!Tools.isInteger(recharage_edit.getText().toString().trim())){
                    Toast.makeText(UserMoneyCenterActivity.this.getApplicationContext(),"请输入整数",Toast.LENGTH_SHORT).show();
                    return;
                }
                switch (radioGroup.getCheckedRadioButtonId()){
                    case R.id.pay_wexin:
                        //       Toast.makeText(UserMoneyCenterActivity.this.getApplicationContext(),"微信支付"
                        //       +   Math.abs(Integer.parseInt(recharage_edit.getText().toString().trim())),Toast.LENGTH_SHORT).show();

                        dialog.dismiss();
                        break;
                    case R.id.pay_paypackage:
                        //        Toast.makeText(UserMoneyCenterActivity.this.getApplicationContext(),"支付宝支付"+  +   Math.abs(Integer.parseInt(recharage_edit.getText().toString().trim())),Toast.LENGTH_SHORT).show();
                        DecimalFormat decimalFormat=new DecimalFormat("0.00");
                        String money=recharage_edit.getText().toString();
                        int realmoney=Integer.parseInt(money);
                        payV2(decimalFormat.format(realmoney),"深圳送宝网科技有限公司-送宝","充值"+realmoney+"元");
                        dialog.dismiss();
                        break;
                }
            }
        });
        recharage_edit =dialog.findViewById(R.id.recharge_edit);
        recharage_edit.setText("");
        RelativeLayout wx_rl=dialog.findViewById(R.id.wx_rl);
        wx_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_wexin.setChecked(true);
            }
        });
        RelativeLayout pay_rl=dialog.findViewById(R.id.pay_rl);
        pay_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pay_paypackage.setChecked(true);
            }
        });
    }


    @OnClick(value = {R.id.backbt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.backbt:
                finish();
                break;

        }
    }

    public class ListAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            return titles.length;
        }

        @Override
        public Object getItem(int i) {
            return titles[i];
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            IndexHolder ih=null;
            if(view==null){
                view=View.inflate(UserMoneyCenterActivity.this, R.layout.listitem_usermoney,null);
                ih=new IndexHolder();
                ih.iv= view.findViewById(R.id.iv);
                ih.title= view.findViewById(R.id.title);
                view.setTag(ih);
                ih.iv.setImageResource(titles_res[i]);
                ih.title.setText(titles[i]);
            }else{
                ih= (IndexHolder) view.getTag();
                ih.iv.setImageResource(titles_res[i]);
                ih.title.setText(titles[i]);
            }

            return view;
        }
        public class IndexHolder{
            public ImageView iv;
            public TextView title;

        }

    }

    public void payV2(String total_account,String title,String content) {
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(HttpUrl.PAY_APPID,total_account,title,content, false);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String privateKey = HttpUrl.PAY_RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, false);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(UserMoneyCenterActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());
                Message msg = new Message();
                msg.what = HttpUrl.SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public void addMoney(String money){
        final List<User> userList= Xutils.queryAll(getApplication(),User.class);
        if(userList==null||userList.size()==0){
            return;
        }
        Map<String,String> map=new HashMap<>();
        map.put("userId",userList.get(0).getUserId()+"");
        map.put("userMoney",money);
        Xutils.POST(HttpUrl.usermodifyaddmoney, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson=new Gson();
                UserDomain userDomain= gson.fromJson(result,UserDomain.class);
                switch (userDomain.getState()){
                    case HttpCode.SUCCESS:
                        webUserServer();
//                        User user= userDomain.getData();
//                        user.setId(userList.get(0).getId());
//                        Xutils.update(getApplication(),user);
                        locationUserServer();
                        break;
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
